<?php

namespace App\Http\Controllers\Api;

use App\Http\Helper\BeanHelper;
use App\Http\Helper\RpcHelper;
use App\Services\OpensslEncryptHelper;
use EasyWeChat\Core\Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Services\IdEncryptService;
use UserTagService;
use TestingConfig;
use TestingDetailService;
use UserRecordService;
use TestingChannelService;

class RpcController extends Controller
{
    public function getUserRecipeTag($tid,$uid, Request $request)
    {
        try {
            $decode = IdEncryptService::encryption($tid,'decode');
            if($decode){
                $tid = $decode[0];
            }
            $decode = IdEncryptService::encryption($uid,'decode');
            if($decode){
                $uid = $decode[0];
            }
            $userTag = [];
            if($userTag = UserTagService::getLatestUserTag($uid,$tid)){
                $userTag['tid'] = IdEncryptService::encryption($userTag['tid'],'encode');
                if(IdEncryptService::encryption($userTag['uid'],'encode')){
                    $uid = IdEncryptService::encryption($userTag['uid'],'encode');
                }
                $userTag['uid'] = $uid;
                unset($userTag['id']);
            }
            return apiSuccess($userTag);
        } catch (Exception $e) {
            return apiError();
        }
    }


    public function addCustomerQuestionnair(Request $request){
        if(!$questionnairId = $request->input('questionnair_id')){
            return apiErrcode('questionnair_id_invalid');
        }
        $result = TestingDetailService::addCustomerQuestionnair($questionnairId);
        return apiSuccess($result);
    }

    /**
     * 减脂平台的同步用户的测评信息
     */
    public function syncQnRecordInfo(Request $request){
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }

        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }

        $businessData = json_decode($businessData,true) ? json_decode($businessData,true) : $businessData;
        if(!isset($businessData['order_id'])){
            return apiErrcode('order_id_invalid');
        }
        if(!isset($businessData['uid'])){
            return apiErrcode('uid_invalid');
        }
        if(!isset($businessData['nutritionist_id'])){
            return apiErrcode('nutritionist_id_invalid');
        }
        $result = UserRecordService::syncUserRecordInfo($businessData['order_id'],$businessData['nutritionist_id'],$businessData["uid"]);
        return apiSuccess($result);

    }


    /**
     * 同步减脂平台的复购订单的
     * http://testing.dev.com/api/jz/sync/purchase/order/qn/info?param=IrxQZQ6uKJK52hsutnOr+xEnyR0PAoWCh3gViweF0iIgj4MCVYilxpX6cc5ocrOTtsUDYYQWnW4oi4lkmjanByuItCE7LWC46JqBk1P3+S9WjYrxYHUS6XH1nUhcvRuv#
     * 业务参数：
     *      origin_order_id ： 原始订单编号
     *      target_order_id ： 目标订单编号
     *      nutri_id ： 营养师编号
     *      tids ： 需要同步的测评编号
     */
    public function syncJzPurchaseOrderQnInfo(Request $request){
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }

        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData,true) ? json_decode($businessData,true) : $businessData;
        if(!isset($businessData['origin_order_id'])){
            return apiErrcode('order_id_invalid');
        }
        $originOrderId = intval($businessData['origin_order_id']);

        if(!isset($businessData['target_order_id'])){
            return apiErrcode('uid_invalid');
        }
        $targetOrderId = intval($businessData['target_order_id']);

        if(!isset($businessData['nutritionist_id'])){
            return apiErrcode('nutritionist_id_invalid');
        }
        $nutriId = intval($businessData['nutritionist_id']);
        if(!isset($businessData['target_nutritionist_id'])){
            return apiErrcode('nutritionist_id_invalid');
        }
        $targetNutriId = intval($businessData['target_nutritionist_id']);
        if(!isset($businessData['tids'])){
            return apiErrcode('tid_invalid');
        }
        $needSyncTids = $businessData['tids'];

        $result = UserRecordService::syncJzPurchaseOrderQnInfo($originOrderId, $targetOrderId, $nutriId, $targetNutriId, $needSyncTids);
        error_log("sync purchase order status =================>".json_encode($result));
        return apiSuccess($result);
    }


    /**
     * 获取减脂平台订单对应的用户测评记录接口
     * 业务参数：
     *      order_id ： 原始订单编号
     *      nutritionist_id ： 营养师编号
     *      uid ： 用户编号
     */
    public function getJzOrderQnRecord(Request $request){
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }

        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData,true) ? json_decode($businessData,true) : $businessData;
        if(!isset($businessData['order_id'])){
            return apiErrcode('order_id_invalid');
        }
        $orderId = $businessData['order_id'];

        if(!isset($businessData['nutritionist_id'])){
            return apiErrcode('nutritionist_id_invalid');
        }
        $nutriId = $businessData['nutritionist_id'];

        if(!isset($businessData['uid'])){
            return apiErrcode('uid_invalid');
        }
        $uid = $businessData['uid'];
        $result = UserRecordService::getJzOrderAvailableQnList($orderId, $nutriId,$uid);
        return apiSuccess($result);
        
    }

    /**
     * 检测免费订单的测评信息
     */
    public function checkFreeOrderQn(Request $request){
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }

        $businessDataJson = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessDataJson){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessDataJson,true);
        $result = UserRecordService::checkFreeOrderQnByUnionId($businessData);
        return apiSuccess($result);
    }

    /**
     * 付费订单同步免费测评
     * @param Request $resuest
     * @return array
     */
    public function syncFreeOrderTestingToPurchase(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }

        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData,true) ? json_decode($businessData,true) : $businessData;

        $targetOrderId = intval(formatArrValue($businessData, 'target_order_id', 0));
        $uid = intval(formatArrValue($businessData, 'uid', 0));
        $nutriId = intval(formatArrValue($businessData, 'nutritionist_id', 0));
        $needSyncFreeTid = intval(formatArrValue($businessData, 'free_tid', 0));
        $needSyncPurchaseTid = intval(formatArrValue($businessData, 'purchase_tid', 0));

        if ($targetOrderId && $uid && $nutriId && $needSyncFreeTid && $needSyncPurchaseTid) {
            $result = UserRecordService::syncFreeOrderTestingToPurchase($targetOrderId, $uid, $nutriId, $needSyncFreeTid, $needSyncPurchaseTid);
            error_log("sync purchase order status =================>".json_encode($result));
            return apiSuccess($result);
        } else {
            return apiErrcode('param_invalid');
        }
    }

    /**
     * 保存渠道
     * @param Request $request
     * @return array
     */
    public function channelAdd(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }
        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData, true) ? json_decode($businessData, true) : $businessData;

        $result = TestingChannelService::store($businessData);
        if ($result) {
            return apiSuccess();
        }
        return apiError();
    }

    /**
     * 修改用户答题记录
     * @param Request $request
     * @return array
     * @throws \App\Exceptions\UserException
     */
    public function fixUserRecord(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }
        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $result = json_decode($businessData, true);
        $businessData = $result === false ? $businessData : $result;

        $result = RpcHelper::fixUserRecord($businessData['order_id'], $businessData['tid'], $businessData['index'], $businessData['answer'], $businessData['weight']);
        if ($result) {
            return apiSuccess();
        }
        return apiError();
    }

    /**
     * 获取测评的基本信息
     * @param Request $request
     * @return array
     * @throws \App\Exceptions\UserException
     */
    public function getTestingBaseInfo(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }
        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData, true);
        $result = RpcHelper::getTestingBaseInfo($businessData['tid'], $businessData['order_id'], $businessData['nutritionist_id']);
        if ($result) {
            return apiSuccess($result);
        }
        return apiError();
    }

    /**
     * 获取订单的测评信息
     * @param Request $request
     * @return array
     * @throws \App\Exceptions\UserException
     */
    public function getOrderTestingInfo(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }
        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData, true);
        $result = RpcHelper::getUserTestingInfo($businessData['tid'], $businessData['order_id'], $businessData['nutritionist_id']);
        if ($result) {
            return apiSuccess($result);
        }
        return apiError();
    }

    /**
     * 获取测评订单的 PD 值
     * @param Request $request
     * @return array
     * @throws \App\Exceptions\UserException
     */
    public function getOrderPDInfo(Request $request) {
        if(!$param = $request->input('param')){
            return apiErrcode('param_invalid');
        }
        $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
        if(!$businessData){
            return apiErrcode('param_invalid');
        }
        $businessData = json_decode($businessData, true);
        $result = RpcHelper::getOrderPDInfo($businessData['tid'], $businessData['order_id'], $businessData['nutritionist_id']);
        if ($result) {
            return apiSuccess($result);
        }
        return apiError();
    }

    /**
     * 同步虚拟订单相关的测评信息
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function syncVirtualOrderRecordInfo(Request $request)
    {
        try{
            if(!$param = $request->input('param')){
                return apiErrcode('param_invalid');
            }
            $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
            if(!$businessData){
                return apiErrcode('param_invalid');
            }
            $businessData = json_decode($businessData, true);
            if(!isset($businessData['order_id'])){
                return apiErrcode('order_id_invalid');
            }

            if(!isset($businessData['nutritionist_id'])){
                return apiErrcode('nutritionist_id_invalid');
            }
            $result = RpcHelper::syncVirtualOrderRecordInfo($businessData);
            return apiSuccess($result);
        }catch (Exception $exception){
            return apiJson($exception->getCode(),$exception->getTraceAsString(),$exception->getMessage());
        }
    }

    /**
     * 获取所有的五维测评列表
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function getFiveDimensionQnList(Request $request)
    {
        try{
            if(!$param = $request->input('param')){
                return apiErrcode('param_invalid');
            }
            $businessData = OpensslEncryptHelper::decryptWithOpenssl($param);
            if(!$businessData){
                return apiErrcode('param_invalid');
            }
            $result = RpcHelper::getFiveDimensionQnList();
            return apiSuccess($result);
        }catch (Exception $exception){
            return apiJson($exception->getCode(), $exception->getTraceAsString(), $exception->getMessage());
        }
    }

    /**
     * 根据手机号获取形体测评的结果信息
     * @param Request $request
     * @param $tid
     * @param $phone
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \App\Exceptions\UserException
     */
    public function physiqueResultPhone(Request $request, $tid, $phone) {
        try{
            //处理第三方uid对应的逻辑。判断uid是否为第三方的uid还是为我们帐号中心的uid
            if($decodeData = IdEncryptService::encryption($tid,'decode')){
                $tid = $decodeData[0];
            }
            //处理第三方uid对应的逻辑。判断uid是否为第三方的uid还是为我们帐号中心的uid
            if($decodeData = IdEncryptService::encryption($phone,'decode')){
                $phone = $decodeData[0];
            }
            list($result, $data) = RpcHelper::getPhysiqueResultByPhone($tid, $phone);
            if (!$result) {
                return apiErrcode($data);
            }
            return apiSuccess(array_values($data));
        }catch (Exception $exception){
            return apiJson($exception->getCode(), $exception->getTraceAsString(), $exception->getMessage());
        }
    }
}
